﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using HCQ2_Common;
using HCQ2_Common.Bean;
using HCQ2_Common.Constant;
using HCQ2_Model;
using HCQ2_Model.ViewModel;
using HCQ2_Model.ViewModel.SysAdmin;
using HCQ2_Model.SysUserModel;
using HCQ2_Common.Encrypt;
using System.IO;
using System.Diagnostics;
using System.Linq;
using System.Text;
using HCQ2_Model.VR.Model;

namespace HCQ2UI_Logic
{
    /// <summary>
    ///  系统设置>用户管理
    /// </summary>
    public class SysUserController:BaseLogic
    {
        //*********************************用户管理*****************************************
        #region 1.0 用户管理首次进入页面 +ActionResult List()
        /// <summary>
        ///  用户管理首次进入页面
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Element]
        [HCQ2_Common.Attributes.Load]
        [HttpGet]
        public ActionResult List()
        {
            //获取当前用户 所属区域及子区域个数统计 系统用户没有区域
            int areaCount = operateContext.bllSession.T_OrgFolder.GetAreaCountByID(operateContext.Usr.user_id);
            if (areaCount == 0 || areaCount > 1)
            {
                //系统用户
                ViewBag.UserType = "systemUser";
                ViewBag.areaCode = "0";//区域代码
            }  
            else
            {
                //社工用户
                ViewBag.UserType = "socialUser";
                var query = operateContext.bllSession.T_Org_User.Select(s => s.user_id == operateContext.Usr.user_id);
                ViewBag.areaCode = query[0].UnitID;//区域代码
            }   
            return View();
        }
        #endregion

        #region 1.1 获取用户一栏数据 +ActionResult GetUserData()
        /// <summary>
        ///  获取用户一栏数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetUserData()
        {
            string keyword = RequestHelper.GetDeStrByName("userName"),//用户名
                roleCode = RequestHelper.GetStrByName("roleCode"),//角色代码
                orgUnit = RequestHelper.GetDeStrByName("orgUnit"),//单位
                inDate = RequestHelper.GetStrByName("inDate"),//注册开始日期
                outDate = RequestHelper.GetStrByName("outDate");//注册截止日期
            int page = RequestHelper.GetIntByName("page"),
               rows = RequestHelper.GetIntByName("rows"),
               status=RequestHelper.GetIntByName("status"),//状态 -1：全部，0：禁用，1：正常
               folder_id = RequestHelper.GetIntByName("folder_id");//区域代码
            List<UserModel> user = base.operateContext.bllSession.T_User.GetUserData(folder_id, Helper.strToSqlStr(keyword), orgUnit, page, rows, inDate, outDate, roleCode, status);
            TableModel tModel = new TableModel()
            {
                total = operateContext.bllSession.T_User.GetCountByData(keyword, folder_id,orgUnit),
                rows = user
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        } 
        #endregion

        #region 1.2.1 单个：添加用户 + ActionResult AddUser(UserModel user)
        /// <summary>
        ///  添加用户
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddUser(UserModel user)
        {
            ModelState.Remove("orgUnit");
            ModelState.Remove("buy_gold");
            ModelState.Remove("give_gold");
            if (!ModelState.IsValid)
                return operateContext.RedirectAjax(1, "数据验证失败~", "", "");
            try
            {
                string roles = Helper.ToString(Request["user_role"]);
                user.user_role = roles;
                //添加之前判断登录名是否被占用
                List<T_User> usr =
                    operateContext.bllSession.T_User.Select(
                        s => s.login_name.Equals(user.login_name, StringComparison.CurrentCultureIgnoreCase));
                if (null != usr && usr.Count > 0)
                    return operateContext.RedirectAjax(1, "添加用户失败，当前登录用户已存在，请重新设置登录名！", "", "");
                bool Isback = base.operateContext.bllSession.T_User.AddUser(user);
                if (Isback)
                    return operateContext.RedirectAjax(0, "添加用户成功~", "", "");
                return operateContext.RedirectAjax(1, "添加用户失败~", "", "");
            }
            catch (Exception ex){
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }    
        }
        #endregion

        #region 1.2.2 批量：添加用户 + ActionResult BatchAddUser(batchUserModel user)
        /// <summary>
        ///  添加用户
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult BatchAddUser(batchUserModel user)
        {
            ModelState.Remove("orgUnit");
            ModelState.Remove("buyGold");
            ModelState.Remove("giveGold");
            if (!ModelState.IsValid)
                return operateContext.RedirectAjax(1, "数据格式验证失败~", "", "");
            try
            {
                if (user.userLen <= 0 || user.userLen > 50)
                    return operateContext.RedirectAjax(1, "创建用户数量必须大于零小于50！", "", "");
                int userCount = operateContext.bllSession.T_User.SelectCount(s => s.batch_user == true);
                for (int i = 0; i < user.userLen; i++)
                {
                    int len = i + 1 + userCount;
                    T_User tempUser = new T_User
                    {
                        user_name = user.loginUser + len.ToString(),
                        login_name = user.loginUser + len.ToString(),
                        user_pwd = EncryptHelper.Md5Encryption(user.loginPwd),
                        user_sex = user.userSex,
                        user_guid = EncryptHelper.CreateGuidValue(),
                        reg_from = 0,
                        status = 1,
                        create_date = DateTime.Now,
                        update_date = DateTime.Now,
                        max_machine = user.maxMachine,
                        buy_gold = user.buyGold,
                        give_gold = user.giveGold,
                        batch_user = true,
                        unit_code = user.unitCode,
                        user_unit = user.userUnit
                    };
                    operateContext.bllSession.T_User.Add(tempUser);
                }
                return operateContext.RedirectAjax(0, "批量添加用户成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 1.2.3 批量导入：添加用户 + ActionResult ImportUser(HttpPostedFileBase excelFile)
        /// <summary>
        ///  添加用户
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ImportUser(HttpPostedFileBase excelFile)
        {
            try
            {
                if (excelFile == null)
                    return operateContext.RedirectAjax(1, "请选择导入文件！", "", "");
                if (!Path.GetExtension(excelFile.FileName).Equals(".xlsx"))
                    return operateContext.RedirectAjax(1, "导入文件是.xlsx格式的excel文件！", "", "");
                //新的文件名
                string batchCode = Helper.GetGuid;
                #region 导入文件到临时目录
                string path = Server.MapPath("~/UpFile/ImportWord/temp/");
                if (!Directory.Exists(path.ToString()))
                    Directory.CreateDirectory(path.ToString());//文件夹不存在则创建
                string tempPath = Server.MapPath("~/UpFile/ImportWord/temp/") + batchCode + ".xlsx";
                excelFile.SaveAs(tempPath);
                #endregion
                Stopwatch sw1 = new Stopwatch();
                sw1.Start();
                bool importUser;
                List<string> mess = operateContext.bllSession.T_User.importUser(tempPath,out importUser);
                sw1.Stop();
                if (importUser)
                    return operateContext.RedirectAjax(0, string.Format("导入成功 用时：{0}秒。", Math.Round((double)sw1.ElapsedMilliseconds / 1000, 2)), (mess.Count > 0 ? mess : null), "");
                //导入成功删除临时文件
                if (System.IO.File.Exists(tempPath))
                    System.IO.File.Delete(tempPath);
                return operateContext.RedirectAjax(1, "数据导入失败~", mess, "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 1.2.3 获取批量创建对象数量 +ActionResult GetBatchNum()
        /// <summary>
        ///  获取批量创建对象数量
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetBatchNum()
        {
            int num = operateContext.bllSession.T_User.SelectCount(s => s.batch_user == true);
            return operateContext.RedirectAjax(0, "获取数据成功~", (num+1), "");
        }
        #endregion

        #region 1.3.1 编辑用户数据 + ActionResult EditUser(UserModel user)
        /// <summary>
        ///  编辑用户数据
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditUser(UserModel user)
        {
            if (!ModelState.IsValid)
                return operateContext.RedirectAjax(1, "数据验证失败~", "", "");
            int user_id = Helper.ToInt(Request["user_id"]);
            string roles = Helper.ToString(Request["user_role"]);
            user.user_role = roles;
            if (user_id<=0)
                return operateContext.RedirectAjax(1, "编辑用户主键值为空~", "", "");
            bool IsBack = true;
            //编辑之前判断登录名是否被占用
            List<T_User> usr =
                operateContext.bllSession.T_User.Select(
                    s =>
                        s.login_name.Equals(user.login_name, StringComparison.CurrentCultureIgnoreCase) &&
                        s.user_id != user.user_id);
            if (null != usr && usr.Count>0 && usr[0].user_id!=user.user_id)
                return operateContext.RedirectAjax(1, "编辑用户失败，登录名已被占用请重新设置登录名！", "", "");
            string selUnit = Helper.ToString(Request["selUnit"]);
            try { 
                IsBack = base.operateContext.bllSession.T_User.EditUser(user, user_id, selUnit);
            }
            catch(Exception ex) { 
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
            if (IsBack)
                return operateContext.RedirectAjax(0, "编辑用户成功~", "", "");
            return operateContext.RedirectAjax(1, "编辑用户失败~", "", "");
        }
        #endregion

        #region 1.3.1 编辑用户数据 + ActionResult EditMainUser(UserModel user)
        /// <summary>
        ///  编辑用户数据
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditMainUser(UserModel user)
        {
            if (!ModelState.IsValid)
                return operateContext.RedirectAjax(1, "数据验证失败~", "", "");
            //编辑之前判断登录名是否被占用
            int mark = operateContext.bllSession.T_User.SelectCount(
                    s => s.login_name.Equals(user.login_name, StringComparison.CurrentCultureIgnoreCase) && s.user_id != user.user_id);
            if (mark > 0)
                return operateContext.RedirectAjax(1, "编辑用户失败，登录名已被占用请重新设置登录名！", "", "");
            T_User u = new T_User
            {
                login_name = user.login_name,
                user_sex = user.user_sex,
                user_qq = user.user_qq,
                user_email = user.user_email,
                user_birth = (!string.IsNullOrEmpty(user.user_birth) ? DateTime.ParseExact(user.user_birth, "yyyy-MM-dd", new System.Globalization.CultureInfo("zh-CN")) : (DateTime?)null),
                user_phone = user.user_phone,
                user_address = user.user_address,
                user_note = user.user_note,
                update_date = DateTime.Now
            };
            operateContext.bllSession.T_User.Modify(u, s => s.user_id == user.user_id, "login_name", "user_sex", "user_qq", "user_email", "user_birth", "user_phone", "user_address", "user_note", "update_time", "update_name");
            if (user.user_id == operateContext.Usr.user_id)
                operateContext.Usr = operateContext.bllSession.T_User.FindSingle(s => s.user_id == user.user_id);
            return operateContext.RedirectAjax(0, "编辑用户成功~", "", "");
        }
        #endregion

        #region 1.3.2 个人重置密码 + ActionResult ModifyUserPassword(ModifyUser user)
        /// <summary>
        ///  个人重置密码
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ModifyUserPassword(ModifyUser param)
        {
            if (!ModelState.IsValid)
                return operateContext.RedirectAjax(1, "数据验证失败~", "", "");
            string oldPassword = EncryptHelper.Md5Encryption(param.oldPassword);
            string newPassword = EncryptHelper.Md5Encryption(param.newPassword);
            if (oldPassword.Equals(newPassword))
                return operateContext.RedirectAjax(1, "新密码和原始密码相同，请重新设置新密码~", "", "");
            T_User user = operateContext.bllSession.T_User.FindSingle(s => s.user_id == operateContext.Usr.user_id);
            //判断旧密码是否正确
            if (!oldPassword.Equals(user.user_pwd))
                return operateContext.RedirectAjax(1, "旧密码错误~", "", "");
            operateContext.bllSession.T_User.Modify(new T_User { user_pwd = newPassword }, s => s.user_id == user.user_id, "user_pwd");
            return operateContext.RedirectAjax(0, "密码更新成功~", "", "");
        }
        #endregion

        #region 1.4 删除用户数据 +ActionResult DelUser(int id)
        /// <summary>
        ///  删除用户数据
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelUserById(int id)
        {
            if(id<=0)
                return operateContext.RedirectAjax(1, "需要删除的数据不存在~", "", "");
            if(operateContext.Usr.user_id==id)
                return operateContext.RedirectAjax(1, "不能删除当前登录者自己的账号~", "", "");
            List<T_User> user = operateContext.bllSession.T_User.Select(s => s.user_id == id);

            //HCQ2UI_Helper.UnitHelper.unitWork.Delete<T_User>(s => s.user_id == id);
            //HCQ2UI_Helper.UnitHelper.unitWork.Delete<T_UserRoleRelation>(s => s.user_id == id);
            //HCQ2UI_Helper.UnitHelper.unitWork.Delete<T_UserGroupRelation>(s => s.user_id == id);
            //HCQ2UI_Helper.UnitHelper.unitWork.Delete<T_Org_User>(s => s.user_id == id);
            //HCQ2UI_Helper.UnitHelper.unitWork.Save();

            int delCount = operateContext.bllSession.T_User.Delete(s => s.user_id == id);
            //1.删除用户对应的角色
            operateContext.bllSession.T_UserRoleRelation.Delete(s => s.user_id == id);
            //2.删除用户对应的组表
            operateContext.bllSession.T_UserGroupRelation.Delete(s => s.user_id == id);
            //3.删除度度圈用户
            operateContext.bllSession.DD_User.Delete(s => s.du_id == id);

            //3.判断原来是否有上传过头像文件，有则删除
            if (!string.IsNullOrEmpty(user[0].user_img) && user[0].user_img.IndexOf("http")<0)
                System.IO.File.Delete(Server.MapPath(user[0].user_img));
            //4.删除对应的组织结构关联关系
            operateContext.bllSession.T_Org_User.Delete(s => s.user_id == id);
            //return operateContext.RedirectAjax(0, "数据删除成功~", "", "");
            if (delCount > 0)
                return operateContext.RedirectAjax(0, "数据删除成功~", "", "");
            return operateContext.RedirectAjax(1, "数据删除失败~", "", "");
        } 
        #endregion

        #region 1.5 根据主键ID获取用户对象 + ActionResult GetEditDataById(string id)
        /// <summary>
        ///  根据主键ID获取用户对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetEditDataById(int id)
        {
            List<T_User> user = operateContext.bllSession.T_User.Select(s => s.user_id == id);
            return operateContext.RedirectAjax(0, "数据获取成功~", user, "");
        }
        #endregion

        #region 1.6 验证用户是否存在 +public ActionResult CheckUser()
        /// <summary>
        ///  验证用户是否存在
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckUser()
        {
            string login_name = Helper.ToString(Request["login_name"]);
            if (string.IsNullOrEmpty(login_name))
                return operateContext.RedirectAjax(1, "登录名为空~", "", "");
            int count =
                operateContext.bllSession.T_User.SelectCount(s => s.login_name == HttpUtility.UrlDecode(login_name));
            if (count > 0)
                return operateContext.RedirectAjax(1, "登录名已存在请重新输入~", "", "");
            return operateContext.RedirectAjax(0, "登录名可以使用~", "", "");
        }
        #endregion

        #region 1.7 激活用户 +ActionResult ActUserById(int id)
        /// <summary>
        ///  激活用户
        /// </summary>
        /// <returns></returns>
        public ActionResult ActUserById()
        {
            int id = RequestHelper.GetIntByName("id"),//受限表id
                user_id = RequestHelper.GetIntByName("user_id");//用户ID
            if (id <= 0 && user_id <= 0)
                return operateContext.RedirectAjax(1, "待激活对象异常~", "", "");
            //1.0 删除受限表
            int count = 0;
            if (id > 0)
                count = operateContext.bllSession.T_LimitUser.Delete(s => s.id == id);
            //2.0 修改个人状态
            int temp = operateContext.bllSession.T_User.Modify(new T_User { status = 1 }, s => s.user_id == user_id, "status");
            if (count <= 0 && temp <= 0)
                return operateContext.RedirectAjax(1, "激活失败~", "", "");
            //写入操作日志表
            operateContext.bllSession.T_LogSeting.Add(new T_LogSeting() {folder_id=1,business_name="用户管理",table_name= "T_LimitUser",primary_key="",user_id= operateContext.Usr.user_id,log_note="激活用户" });
            return operateContext.RedirectAjax(0, "激活成功~", "", "");
        }
        #endregion

        #region 1.8 用户管理 获取单位树数据 + ActionResult GetUserUnitTreeData()
        /// <summary>
        ///  用户管理 获取单位树数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetUserUnitTreeData()
        {
            return operateContext.RedirectAjax(0, "成功", operateContext.bllSession.T_User.GetAreaData(operateContext.Usr.user_id), "");
        }
        #endregion

        #region 2.0 根据用户ID获取登录信息 + ActionResult GetLoginMessageData(int id)
        /// <summary>
        ///  根据用户ID获取登录信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLoginMessageData()
        {
            T_Login loginObj = operateContext.bllSession.T_Login.selectLoginById(operateContext.Usr.user_id);
            if(loginObj==null)
                return operateContext.RedirectAjax(1, "没有登录信息", "", "");
            return operateContext.RedirectAjax(0, "成功获取登录信息", loginObj, "");
        }
        #endregion

        #region  2.1 重置密码 + ActionResult ResetPassWord(UserModel user)
        /// <summary>
        ///  2.1 重置密码
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ResetPassWord(UserModel user)
        {
            if (!ModelState.IsValid)
                return operateContext.RedirectAjax(1, "数据验证失败~", "", "");
            operateContext.bllSession.T_User.Modify(new T_User { user_pwd = EncryptHelper.Md5Encryption(user.user_pwd) }, s => s.user_id == user.user_id, "user_pwd");
            return operateContext.RedirectAjax(0, "重置密码成功~", "", "");
        }
        #endregion

        #region  2.2 给用户充值金额 + ActionResult RechargeByUser()
        /// <summary>
        ///  2.1 给用户充值金额
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RechargeByUser()
        {
            string userid = RequestHelper.GetStrByName("userID");
            int buyGold = RequestHelper.GetIntByName("buyGold"),//购买金额
                giveGold = RequestHelper.GetIntByName("giveGold");//赠送金额
            if(string.IsNullOrEmpty(userid))
                return operateContext.RedirectAjax(1, "用户关键id值为空~", "", "");
            List<T_User> list = operateContext.bllSession.T_User.GetUserList(userid);
            int create_id = operateContext.Usr.user_id;
            string create_name = operateContext.Usr.user_name;
            DateTime create_date = DateTime.Now;
            list.ForEach(s => {
                decimal buy_gold = s.buy_gold, //变动前金币
                give_gold = s.give_gold;//变动前赠币
                decimal _buy_gold = buy_gold + buyGold,//变动后金币
                _give_gold = give_gold + giveGold;//变动后赠币
                s.buy_gold = _buy_gold;
                s.give_gold = _give_gold;
                operateContext.bllSession.T_User.Modify(s, o => o.user_id == s.user_id, "buy_gold", "give_gold");
                //购买V金币
                if (buyGold > 0)
                    operateContext.bllSession.T_VRGoldLog.Add(new T_VRGoldLog { user_id = s.user_id, user_name = s.user_name, unit_code = s.unit_code, gold_num = (_buy_gold - buy_gold), gold_type = 1, operator_type = 1, create_id = create_id, create_name = create_name, create_date = create_date, BeforBuyGold= buy_gold, BuyGold= _buy_gold});
                //赠送币
                if (giveGold > 0)
                    operateContext.bllSession.T_VRGoldLog.Add(new T_VRGoldLog { user_id = s.user_id, user_name = s.user_name, unit_code = s.unit_code, gold_num = (_give_gold - give_gold), gold_type = 2, operator_type = 1, create_id = create_id, create_name = create_name, create_date = create_date, BeforGiveGold = give_gold, GiveGold = _give_gold });
            });
            //判断充值者是否需要更新用户等级
            //UserLevelColumn level = operateContext.bllSession.T_VRUserLevel.ResetUserLevel(create_id, DateTime.Now.Year);
            //operateContext.bllSession.T_User.Modify(new T_User { sell_money = level.saleNum, line_num = level.lineNum, user_level = level.userLevel }, s => s.user_id == create_id, "sell_money", "line_num", "user_level");
            //if(level.userLevel> operateContext.Usr.user_level)
            //{
            //    //等级发生变动写入：等级日志表
            //    operateContext.bllSession.T_VRUserLevelLog.Add(new T_VRUserLevelLog { user_id = create_id, user_name = create_name, user_level = level.userLevel, sell_money = level.saleNum, line_num = level.lineNum, create_id = create_id, create_name = create_name, create_date = DateTime.Now });
            //}
            return operateContext.RedirectAjax(0, "充值成功~", "", "");
        }
        #endregion

        //*********************************用户--角色设置*****************************************
        #region 3.0 用户--角色设置页面首次跳转 +ActionResult UserRoleList()
        /// <summary>
        ///  用户--角色设置页面首次跳转
        /// </summary>
        /// <returns></returns>
        public ActionResult UserRoleList()
        {
            return View();
        }
        #endregion

        #region 3.1 根据用户ID 获取对于角色数据 +ActionResult GetUserRoleData(int id)
        /// <summary>
        ///  根据用户ID 获取对于角色数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetUserRoleData(int id)
        {
            //ID对应角色
            List<T_UserRoleRelation> list = operateContext.bllSession.T_UserRoleRelation.GetUserRoleData(id);
            if (list == null || list.Count == 0)
                return operateContext.RedirectAjax(1, "获取角色信息为空~", "", "");
            return operateContext.RedirectAjax(0, "成功获取角色信息", list, "");
        }
        #endregion

        #region 3.2 获取所有角色 +ActionResult GetUserRoleData()
        /// <summary>
        ///  获取所有角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetAllRoleData()
        {
            int page = Helper.ToInt(Request["page"]);
            int rows = Helper.ToInt(Request["rows"]);
            //所有角色
            List<T_Role> list = operateContext.bllSession.T_Role.Select(s => (!string.IsNullOrEmpty(s.role_name)),
                s => s.role_name, page, rows, true);
            TableModel tModel = new TableModel()
            {
                total = operateContext.bllSession.T_Role.SelectCount(null),
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 3.3  保存用户--角色设置 + ActionResult SaveUserRoleData(FormCollection form, int id)
        /// <summary>
        ///  保存用户--角色设置
        /// </summary>
        /// <param name="form"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveUserRoleData(FormCollection form, int id)
        {
            string roles = Helper.ToString(form["roleData"]);
            try
            {
                bool back = operateContext.bllSession.T_UserRoleRelation.SaveUserRoleData(roles,id);
                //清理角色缓存
                SessionHelper.RemoveSession(CacheConstant.loginUserCacheRoles);
                if (back)
                    return operateContext.RedirectAjax(0, "保存数据成功~", "", "");
                return operateContext.RedirectAjax(1, "保存数据失败~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 3.4  批量保存角色 + ActionResult SaveUserBatchRoleData()
        /// <summary>
        ///  批量保存角色
        /// </summary>
        /// <param name="form"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveUserBatchRoleData()
        {
            string userid = RequestHelper.GetStrByName("userid"),//用户id
                roleData = RequestHelper.GetStrByName("roleData");//角色数据
            try
            {
                if(string.IsNullOrEmpty(userid))
                    return operateContext.RedirectAjax(1, "保存数据异常~", "", "");
                userid = userid.Trim().Trim(',');
                string[] ids = userid.Trim().Split(',');
                if (string.IsNullOrEmpty(roleData))
                {
                    //清空人员全部角色
                    foreach (var id in ids)
                    {
                        int user_id = Helper.ToInt(id);
                        operateContext.bllSession.T_UserRoleRelation.Delete(s => s.user_id == user_id);
                    }
                    return operateContext.RedirectAjax(0, "角色清理成功~", "", "");
                }
                string[] roles = roleData.Trim().Trim(',').Split(',');
                List<T_UserRoleRelation> list = operateContext.bllSession.T_UserRoleRelation.GetUserRoleList(userid);
                //循环人员
                foreach(var id in ids)
                {
                    var temp = list.Where(s => s.user_id == Helper.ToInt(id));
                    StringBuilder sb = new StringBuilder();
                    foreach (var role_id in roles)
                    {
                        var roleCount = temp.Where(o => o.role_id == Helper.ToInt(role_id))?.Count();
                        if (roleCount == null || roleCount <= 0)
                            sb.Append($"INSERT INTO T_UserRoleRelation(user_id,role_id) VALUES({id},{role_id});");
                    }
                    if (!string.IsNullOrEmpty(sb.ToString()))
                        HCQ2_Common.SQL.SqlHelper.ExecuteNonQuery(sb.ToString());
                }
                //清理角色缓存
                SessionHelper.RemoveSession(CacheConstant.loginUserCacheRoles);
                return operateContext.RedirectAjax(0, "保存数据成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 3.5  批量添加角色 + ActionResult SaveUserAddBatchRoleData()
        /// <summary>
        ///  批量添加角色
        /// </summary>
        /// <param name="form"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveUserAddBatchRoleData()
        {
            string userid = RequestHelper.GetStrByName("userid"),//用户id
                roleData = RequestHelper.GetStrByName("roleData");//角色数据
            if (string.IsNullOrEmpty(userid))
                return operateContext.RedirectAjax(1, "需要分配的人员数据为空~", "", "");
            if (string.IsNullOrEmpty(roleData))
                return operateContext.RedirectAjax(0, "请勾选需要添加的角色~", "", "");
            try
            {
                userid = userid.Trim().Trim(',');
                string[] ids = userid.Trim().Split(',');
                string[] roles = roleData.Trim().Trim(',').Split(',');
                List<T_UserRoleRelation> list = operateContext.bllSession.T_UserRoleRelation.GetUserRoleList(userid);
                //循环人员
                foreach (var id in ids)
                {
                    var temp = list.Where(s => s.user_id == Helper.ToInt(id));
                    StringBuilder sb = new StringBuilder();
                    foreach (var role_id in roles)
                    {
                        var roleCount = temp.Where(o => o.role_id == Helper.ToInt(role_id))?.Count();
                        if (roleCount == null || roleCount <= 0)
                            sb.Append($"INSERT INTO T_UserRoleRelation(user_id,role_id) VALUES({id},{role_id});");
                    }
                    if (!string.IsNullOrEmpty(sb.ToString()))
                        HCQ2_Common.SQL.SqlHelper.ExecuteNonQuery(sb.ToString());
                }
                //清理角色缓存
                SessionHelper.RemoveSession(CacheConstant.loginUserCacheRoles);
                return operateContext.RedirectAjax(0, "保存数据成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 3.6  批量更新角色 + ActionResult SaveUserMondifyBatchRoleData()
        /// <summary>
        ///  批量更新角色
        /// </summary>
        /// <param name="form"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveUserMondifyBatchRoleData()
        {
            string userid = RequestHelper.GetStrByName("userid"),//用户id
                roleData = RequestHelper.GetStrByName("roleData");//角色数据
            if (string.IsNullOrEmpty(userid))
                return operateContext.RedirectAjax(1, "需要分配的人员数据为空~", "", "");
            try
            {
                userid = userid.Trim().Trim(',');
                string[] ids = userid.Trim().Split(',');
                if (string.IsNullOrEmpty(roleData))
                {
                    //清空人员全部角色
                    foreach (var id in ids)
                    {
                        int user_id = Helper.ToInt(id);
                        operateContext.bllSession.T_UserRoleRelation.Delete(s => s.user_id == user_id);
                    }
                    return operateContext.RedirectAjax(0, "角色清理成功~", "", "");
                }
                string[] roles = roleData.Trim().Trim(',').Split(',');
                List<T_UserRoleRelation> list = operateContext.bllSession.T_UserRoleRelation.GetUserRoleList(userid);
                //循环人员
                foreach (var id in ids)
                {
                    var temp = list.Where(s => s.user_id == Helper.ToInt(id));
                    StringBuilder sb = new StringBuilder();
                    foreach (var role_id in roles)
                    {
                        var roleCount = temp.Where(o => o.role_id == Helper.ToInt(role_id))?.Count();
                        if (roleCount == null || roleCount <= 0)
                            sb.Append($"INSERT INTO T_UserRoleRelation(user_id,role_id) VALUES({id},{role_id});");
                    }
                    //添加未配置的角色
                    if (!string.IsNullOrEmpty(sb.ToString()))
                        HCQ2_Common.SQL.SqlHelper.ExecuteNonQuery(sb.ToString());
                    //删除未选中的角色
                    HCQ2_Common.SQL.SqlHelper.ExecuteNonQuery($"delete from T_UserRoleRelation where user_id={id} and role_id not in({roleData.Trim().Trim(',')});");
                }
                //清理角色缓存
                SessionHelper.RemoveSession(CacheConstant.loginUserCacheRoles);
                return operateContext.RedirectAjax(0, "保存数据成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 3.5  批量启用用户 + ActionResult SaveUserBatchStart()
        /// <summary>
        ///  批量启用用户
        /// </summary>
        /// <param name="form"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveUserBatchStart()
        {
            string userid = RequestHelper.GetStrByName("userid");//用户id
            try
            {
                if (string.IsNullOrEmpty(userid))
                    return operateContext.RedirectAjax(1, "启用用户数据为空~", "", "");
                userid = userid.Trim().Trim(',');
                string[] ids = userid.Trim().Split(',');
                //循环人员
                foreach (var id in ids)
                {
                    int user_id = Helper.ToInt(id);
                    operateContext.bllSession.T_User.Modify(new T_User { status = 1 }, s => s.user_id == user_id, "status");
                } 
                return operateContext.RedirectAjax(0, "数据启用成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 3.6  批量禁用用户 + ActionResult SaveUserBatchForbid()
        /// <summary>
        ///  批量禁用用户
        /// </summary>
        /// <param name="form"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveUserBatchForbid()
        {
            string userid = RequestHelper.GetStrByName("userid");//用户id
            try
            {
                if (string.IsNullOrEmpty(userid))
                    return operateContext.RedirectAjax(1, "禁用用户数据为空~", "", "");
                userid = userid.Trim().Trim(',');
                string[] ids = userid.Trim().Split(',');
                //循环人员
                foreach (var id in ids)
                {
                    int user_id = Helper.ToInt(id);
                    operateContext.bllSession.T_User.Modify(new T_User { status = 0 }, s => s.user_id == user_id, "status");
                }                   
                return operateContext.RedirectAjax(0, "数据禁用成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        //*********************************用户--分组设置*****************************************

        #region 4.0 用户--用户组设置页面首次跳转 +ActionResult UserGroupList()
        /// <summary>
        ///  用户--用户组设置页面首次跳转
        /// </summary>
        /// <returns></returns>
        public ActionResult UserGroupList()
        {
            return View();
        }
        #endregion

        #region 4.1 根据用户ID 获取对于组数据 +ActionResult GetUserGroupData(int id)
        /// <summary>
        ///  根据用户ID 获取对于组数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetUserGroupData(int id)
        {
            //ID对应用户组
            List<T_UserGroupRelation> list = operateContext.bllSession.T_UserGroupRelation.GetUserGroupData(id);
            if (list == null || list.Count == 0)
                return operateContext.RedirectAjax(1, "获取角色信息为空~", "", "");
            return operateContext.RedirectAjax(0, "成功获取角色信息", list, "");
        }
        #endregion

        #region 4.2 获取所有组数据集合 +ActionResult GetAllGroupData()
        /// <summary>
        ///  获取所有组数据集合
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetAllGroupData()
        {
            int page = Helper.ToInt(Request["page"]);
            int rows = Helper.ToInt(Request["rows"]);
            //所有角色
            List<T_UserGroup> list = operateContext.bllSession.T_UserGroup.Select<int>(s => (!string.IsNullOrEmpty(s.group_name)),
                s => s.group_id, page, rows, true);
            TableModel tModel = new TableModel()
            {
                total = operateContext.bllSession.T_UserGroup.SelectCount(null),
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 4.3  保存用户--用户组设置 + ActionResult SaveUserGroupData(FormCollection form, int id)
        /// <summary>
        ///  保存用户--用户组设置
        /// </summary>
        /// <param name="form"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveUserGroupData(FormCollection form, int id)
        {
            string users = Helper.ToString(form["userData"]);
            try
            {
                bool back = operateContext.bllSession.T_UserGroupRelation.SaveUserGroupData(users, id);
                //清理角色缓存
                SessionHelper.RemoveSession(CacheConstant.loginUserCacheRoles);
                if (back)
                    return operateContext.RedirectAjax(0, "保存数据成功~", "", "");
                return operateContext.RedirectAjax(1, "保存数据失败~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        //*********************************用户--代管配置*****************************************
        #region 5. 0用户--代管配置首次进入+ActionResult UserProxy()
        /// <summary>
        ///  用户--代管配置首次进入
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        public ActionResult UserProxy()
        {
            return View();
        }
        #endregion

        #region 5.1 异步获取单位树zTree方式 +ActionResult GetUnitTreeData()
        /// <summary>
        ///  异步获取单位树zTree方式
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetUnitTreeData(int id)
        {
            return null;
            //List<Dictionary<string, object>> list = operateContext.bllSession.T_UserUnitRelation.GetUserAreaAndPersonById(id);
            //return Json(list, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 5.2 用户管理代管配置 +ActionResult GetProUnitTreeData()
        /// <summary>
        ///  用户管理代管配置
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetProUnitTreeData(int id)
        {
            return null;
        }
        #endregion 

        #region 5.2 保存用户--代管设置 +ActionResult SaveUserUnitData(FormCollection form, int id)
        /// <summary>
        ///  保存用户--代管设置
        /// </summary>
        /// <param name="form"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveUserUnitData(FormCollection form, int id)
        {
            return operateContext.RedirectAjax(1, "保存数据失败~", "", "");
        }
        #endregion
    }
}
